package com.pansoft.openplanet.activity.child;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.baseadapter.listview.CommonAdapter;
import com.efounder.baseadapter.listview.ViewHolder;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ResStringUtil;
import com.pansoft.nfc.mifare.Common;
import com.pansoft.nfc.mifare.activity.MifareNfcMessageActivity;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.BleBlutoothScanActivity;
import com.pansoft.openplanet.activity.ChooseWalletTypeActivity;
import com.pansoft.openplanet.activity.TCBaseActivity;
import com.pansoft.openplanet.bean.CreateChildWalletBean;
import com.pansoft.openplanet.widget.AutoLineFeedLayout;
import com.utilcode.util.SizeUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static android.util.TypedValue.COMPLEX_UNIT_DIP;

/**
 * 确认用户记录下助记词
 * Created by will on 18-4-26.
 */

public class ChildTokenCheckActivity extends TCBaseActivity {

    private String mnemonic;
    private GridView gridView;
    private MyTokenHelperAdapter gridAdapter;
    private List<String> mnemonics;
    private List<String> result_mnemonics = new ArrayList<>();
    private static final String PLACE_HOLDER = "place_holder";
    AutoLineFeedLayout alflMnemonicShow;

    /** 是否是创建卡片冷钱包 **/
    private boolean isCardColdWallet;
    private String address;

    private CreateChildWalletBean childWalletBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_token_check);
        initView();
        initData();
    }

    private void initData() {
        childWalletBean = (CreateChildWalletBean) getIntent().getSerializableExtra("childWalletBean");
        isCardColdWallet = getIntent().getBooleanExtra("isCardColdWallet", false);
        mnemonic = childWalletBean.getMnemonic();
        address = childWalletBean.getWalletAddress();

        mnemonics = new ArrayList<>();
        parseMnemonic();
        result_mnemonics.add(PLACE_HOLDER);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridAdapter = new MyTokenHelperAdapter(this, R.layout.talk_chain_item_token_helper, result_mnemonics);
        gridView.setAdapter(gridAdapter);
        alflMnemonicShow = (AutoLineFeedLayout) findViewById(R.id.alfl_mnemonic_show);
        loadBottomView();
    }

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.openplanet_verify_your_mnemic));
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        gridView = (GridView) findViewById(R.id.gv_token_helper);
        Button tvNext = (Button) findViewById(R.id.tv_next);
        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verifyResult();
            }
        });
    }

    private void loadBottomView() {
//        if (shuffle) {
        Collections.shuffle(mnemonics);
        alflMnemonicShow.removeAllViews();
//        }

        for (int i = 0; i < mnemonics.size(); i++) {
            final LinearLayout linearLayout = new LinearLayout(this);
            final TextView textView = new TextView(this);
            textView.setPadding(SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5));
            textView.setBackgroundColor(getResources().getColor(R.color.op_float_window_color));
            textView.setTextColor(getResources().getColor(R.color.wechat_white_or_black));
            textView.setTextSize(COMPLEX_UNIT_DIP, 17);
            final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(SizeUtils.dp2px(10), SizeUtils.dp2px(5), SizeUtils.dp2px(10), SizeUtils.dp2px(5));
            textView.setText(mnemonics.get(i));
            textView.setLayoutParams(params);
            alflMnemonicShow.addView(linearLayout);
            linearLayout.addView(textView);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addTopView(linearLayout, textView.getText().toString());
                    loadBottomView();
                }
            });

        }
    }

    private void addTopView(final LinearLayout linearLayout, String text) {
        alflMnemonicShow.removeView(linearLayout);
        mnemonics.remove(text);
        if (result_mnemonics.size() == 1 && result_mnemonics.get(0).equals(PLACE_HOLDER)) {
            result_mnemonics.remove(0);
        }
        result_mnemonics.add(text);
        gridAdapter.notifyDataSetChanged();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (result_mnemonics.get(position).equals(PLACE_HOLDER)) {
                    return;
                }
                addBottomView(result_mnemonics.get(position));
            }
        });

    }

    private void addBottomView(String text) {
        final TextView textView1 = new TextView(ChildTokenCheckActivity.this);
        textView1.setPadding(SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5), SizeUtils.dp2px(5));
        textView1.setBackgroundColor(getResources().getColor(R.color.op_float_window_color));
        textView1.setTextColor(getResources().getColor(R.color.wechat_white_or_black));
        textView1.setTextSize(COMPLEX_UNIT_DIP, 17);
        textView1.setText(text);
        mnemonics.add(text);
        result_mnemonics.remove(text);
        if (result_mnemonics.size() == 0) {
            result_mnemonics.add(PLACE_HOLDER);
        }
        gridAdapter.notifyDataSetChanged();
        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(SizeUtils.dp2px(10), SizeUtils.dp2px(5), SizeUtils.dp2px(10), SizeUtils.dp2px(5));
        textView1.setLayoutParams(params);

        final LinearLayout linearLayout1 = new LinearLayout(ChildTokenCheckActivity.this);
        alflMnemonicShow.addView(linearLayout1);
        linearLayout1.addView(textView1);
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addTopView(linearLayout1, textView1.getText().toString());
                loadBottomView();
            }
        });
    }

    private void parseMnemonic() {
        String[] arr = mnemonic.split("\\s+");
        for (String ss : arr) {
            mnemonics.add(ss);
        }
    }

    private void verifyResult() {
        if (mnemonics.size() > 0 && result_mnemonics.size() > 0) {
            showDialog(ResStringUtil.getString(R.string.openplanet_please_check_mnemonic));
            loadBottomView();
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String mnemonic : result_mnemonics) {
            stringBuilder.append(mnemonic).append(" ");
        }
        String result = stringBuilder.toString().trim();
        if (!mnemonic.equals(result)) {
            showDialog(ResStringUtil.getString(R.string.openplanet_chech_zhujici));
            loadBottomView();
            return;
        }
        if (address == null || "".equals(address)) {
            showDialog(ResStringUtil.getString(R.string.openplanet_tokencheck_text1));
            return;
        }

        if (isCardColdWallet) {
            //直接创建卡片冷钱包
            if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                return;
            }
            if (!EnvSupportManager.isSupportForceBleNfc() && Common.hasMifareClassicSupport(this)){
                MifareNfcMessageActivity.start(ChildTokenCheckActivity.this, childWalletBean,
                        BleBlutoothScanActivity.TYPE_CREATE_COLD_WALLET);
                //蓝牙读卡器
            } else {
                BleBlutoothScanActivity.start(this, childWalletBean,
                        BleBlutoothScanActivity.TYPE_CREATE_COLD_WALLET, BleBlutoothScanActivity.BLE_TYPE_NFC);
            }
        } else {
            //选择创建热钱包还是冷钱包
            ChooseWalletTypeActivity.start(this, childWalletBean);
        }
    }


    private void showDialog(String msg) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.common_text_hint)
                .setMessage(msg)
                .setPositiveButton(R.string.common_text_confirm, null)
                .create()
                .show();
    }

    public class MyTokenHelperAdapter extends CommonAdapter<String> {
        public MyTokenHelperAdapter(Context context, int layoutId, List<String> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder viewHolder, String item, int position) {
            if (item.equals(PLACE_HOLDER)) {
                viewHolder.setTextColor(R.id.tv_token_helper, Color.parseColor("#00000000"));
                viewHolder.setBackgroundColor(R.id.tv_token_helper, Color.parseColor("#00000000"));
            } else {
                viewHolder.setTextColor(R.id.tv_token_helper, getResources().getColor(R.color.op_text_white_color));
                viewHolder.setBackgroundRes(R.id.tv_token_helper, R.drawable.rectangle_bg_orange);
            }
            viewHolder.setText(R.id.tv_token_helper, position + 1 + "." + item);
        }
    }
}
